package cn.pkubangbang.demo.democontact.controller;

import cn.pkubangbang.demo.democontact.entity.CommonMessage;
import cn.pkubangbang.demo.democontact.exceptions.ResultNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: zhangzhenbang@k2data.com.cn
 * @Date: 2018-09-03 11:14
 */
@ControllerAdvice
public class ExceptionHandlerControllerAdvice {

    @ExceptionHandler
    @ResponseBody
    public ResponseEntity<CommonMessage> defaultErrorHandling(Exception ex) {
        if (ex instanceof UnsupportedOperationException) {
            CommonMessage commonMessage = new CommonMessage();
            commonMessage.setMessage(ex.getMessage());
            return new ResponseEntity<>(commonMessage, HttpStatus.INTERNAL_SERVER_ERROR);
        } else if (ex instanceof ResultNotFoundException) {
            CommonMessage commonMessage = new CommonMessage();
            commonMessage.setMessage(ex.getMessage());
            return new ResponseEntity<>(commonMessage, HttpStatus.NOT_FOUND);
        }

        CommonMessage defaultMessage = new CommonMessage();
        defaultMessage.setMessage("Unknown Exception Occured.");
        return new ResponseEntity<>(defaultMessage, HttpStatus.I_AM_A_TEAPOT);
    }

}
